<!-- 旅游项目配置 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="项目类型">
                            <a-select v-model="itemType" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in itemTypeList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type="primary" style="margin-right: 20px" @click="getData()">查询</a-button>
                            <a-button type="" icon="plus" @click="add()">添加</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size,}" size="small">
            <div slot="itemType" slot-scope="itemType">
                <div v-for="(item,i) in itemTypeList" :key="item.id">
                    <a-tag v-if="item.id == itemType" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="title" slot-scope="title">
                <ellipsis :length="18" tooltip>{{ title.title }}</ellipsis>
            </div>
            <div slot="amount" slot-scope="text,record">
                <ellipsis :length="18" tooltip>{{ record.title.amount }}元</ellipsis>
            </div>
            <div slot="itemInfo" slot-scope="text,record">
                <a-button v-if="hasAuth('updateTravelItemInfo')" type="link" @click="showItemInfo(record)">查看详情</a-button>
                <div v-else>-</div>
            </div>
            <div slot="itemPlan" slot-scope="text,record">
                <a-button type="link" v-if="hasAuth('updateTravelItemPlan')" @click="showItemPlan(record)">查看套餐</a-button>
                <div v-else>-</div>
            </div>
            <div slot="titleImgUrl" slot-scope="text,record">
                <img style="width: 120px;height: 60px" v-if="record.title.titleImgUrl && record.title.titleImgUrl.substring(0,4) == 'http'" :src="record.title.titleImgUrl && record.title.titleImgUrl.split(',')[0]" alt="" @click="showImg(record.title.titleImgUrl)">
                <div v-else>-</div>
            </div>
            <div slot="openOnOff" slot-scope="openOnOff">
                <a-switch checked-children="开" un-checked-children="关" disabled :checked="openOnOff == '1' ? true : false" />
            </div>
            <div slot="operation" slot-scope="text,record">
                <a-button type="link" @click="update(record)">修改</a-button>
                <a-popconfirm
                    title="是否确认删除当前配置?"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="del(record)"
                >
                    <a-button class="errorColor" type="link">删除</a-button>
                </a-popconfirm>
            </div>
        </a-table>

        <a-modal
            title="添加、修改旅游项目标题"
            :visible="visible"
            @ok="handleOk"
            :confirm-loading="confirmLoading"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
                    <a-form-item label="项目类型">
                        <a-select v-model="item.itemType" placeholder="请选择" allowClear>
                            <a-select-option v-for="(item,i) in itemTypeList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="项目标题">
                        <a-input v-model="item.title" placeholder="请输入项目标题" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="项目价格">
                        <a-input v-model="item.amount" placeholder="请输入项目价格" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="轮播图">
                        <div class="clearfix">
                            <a-upload
                                list-type="picture-card"
                                accept="image/*"
                                :file-list="imgList"
                                @preview="handlePreview"
                                @change="imgHandleChange"
                                :before-upload="beforeUpload"
                            >
                                <div v-if="imgList.length < 11">
                                    <a-icon type="plus" />
                                    <div class="ant-upload-text">选择轮播图</div>
                                </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <!-- <a-form-item label="状态">
                        <a-radio-group v-model="item.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item> -->
                </a-form>
            </div>
        </a-modal>

        <!-- 上传图片预览 -->
        <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
        <!-- 表格图片预览 -->
        <a-modal :visible="previewImgVisible" :footer="null" @cancel="previewImgVisible = false">
            <a-carousel autoplay dots-class="slick-dots slick-thumb" arrows style="margin-bottom:60px">
                <div v-for="(img,i) in showImgs" :key="i">
                    <img :src="img" alt=""/>
                </div>
                <a slot="customPaging" slot-scope="props">
                    <img :src="getImgUrl(props.i)" />
                </a>
            </a-carousel>
        </a-modal>
    </div>
</template>

<script>
import { queryTravelItem , updateTravelItem } from '@/api/travel';
import { uploadFile } from '@/api/brand';
import { columns } from './table';
import { Ellipsis } from '@/components';
import { getBase64 } from '@/utils/util';
export default {
    components: {
        Ellipsis,
    },
    data () {
        return {
            brandId: this.global.brandId,
            itemType: undefined,
            itemTypeList: [
                { id: 1, name: '机票套餐'},
                { id: 2, name: '酒店套餐'},
                { id: 4, name: '游艇租赁'},
                { id: 5, name: '尾波冲浪'},
                { id: 6, name: '游艇出海'},
            ],
            dataList: [],
            total: 0,
            isload: false,
            page: 1,
            size: 10,
            columns,
            item: {
                'id': '',
                'title': '', // 标题
                'itemType': undefined, // 项目类型
                'amount': '', // 价格
                'titleImgUrl': '', // 标题图片
            },
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            confirmLoading: false,
            isAdd: false,
            visible: false,
            imgList: [],
            previewVisible: false,
            previewImage: '',
            previewImgVisible: false,
            showImgs: [],
        };
    },
    async created(){
        try {
            this.getData()
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        // 获取旅游项目基本配置
        getData(){
            let _this = this
            _this.isload = true
            const params = {
                'brandId': _this.global.brandId,
                'itemType': _this.itemType,
                'size':_this.size,
                'page':_this.page - 1,
            }
            queryTravelItem(params)
            .then(res=>{
                _this.isload = false
                if(res.success){
                    _this.dataList = res.data.content
                    _this.total = res.data.totalElements
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加
        add(){
            this.isAdd = true;
            this.item.id = '';
            this.item.title = '';
            this.item.amount = '';
            this.item.titleImgUrl = '';
            this.item.itemType = undefined;
            this.imgList = [];
            this.visible = true
        },
        // 修改
        async update(item){
            let _this = this;
            // _this.item = JSON.parse(JSON.stringify(item))
            _this.item.id = item.id;
            _this.item.title = item.title.title;
            _this.item.amount = item.title.amount;
            _this.item.itemType = item.itemType;
            _this.item.titleImgUrl = item.title.titleImgUrl;
            _this.imgList = [];
            if(item.title.titleImgUrl && item.title.titleImgUrl.substring(0,4) == 'http'){
                var array = item.title.titleImgUrl.split(',');
                let _this = this;
                for (let index = 0; index < array.length; index++) {
                    const element = array[index];
                    _this.imgList.push({
                        'uid': index +1,
                        'id': index +1,
                        'url': element,
                        'status':'done',
                        'name':element,
                        'noFile': true,
                    })
                }
            }
            this.isAdd = false;
            this.visible = true
        },
        // 确认添加、修改
        async handleOk(){
            let _this = this
            if(_this.item.itemType === undefined){
                _this.$message.warning('请选择项目类型')
                return;
            }
            if(_this.item.title == ''){
                _this.$message.warning('请输入项目标题')
                return;
            }
            if(_this.item.amount == ''){
                _this.$message.warning('请输入项目价格')
                return;
            }
            if(_this.imgList.length == 0){
                _this.$message.warning('请选择项目图片')
                return;
            }
            var imgList = [];
            if(_this.imgList.length > 0){
                for (let index = 0; index < _this.imgList.length; index++) {
                    const element = _this.imgList[index];
                    console.log(element,'element')
                    if(element.noFile){
                        imgList.push(element.url);
                    }else{
                        try {
                            var imgs = await _this.uploadImg(element.originFileObj,`logo${index}`);
                            console.log(imgs,'imgs');
                            imgList.push(imgs);
                        } catch (error) {
                            _this.$notification['error']({
                                message: '提示',
                                description: error,
                                duration: 8,
                            })
                            return;
                        }
                    }
                }
                _this.item.titleImgUrl = imgList.join(',');
            }
            const params = {
                'itemId': _this.item.id,
                'titleImgUrl': _this.item.titleImgUrl,
                'itemType': _this.item.itemType,
                'title': _this.item.title,
                'amount': _this.item.amount,
                'brandId': _this.brandId,
            }
            updateTravelItem(params)
            .then(async res=>{
                if(res.success){
                    _this.visible = false;
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.isAdd ? '添加成功' : '修改成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 删除
        del(item){
            let _this = this
            const params = {
                'itemId': item.id,
                'name': item.name,
                'itemType': item.itemType,
                'amount': item.amount,
                'titleImgUrl': item.titleImgUrl,
                'isDelete': '1'
            }
            updateTravelItem(params)
            .then(res=>{
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 预览图片
        showImg(imgs){
            if(imgs){
                this.showImgs = imgs.split(',')
                console.log(this.showImgs,'imgs')
                this.previewImgVisible = true
            }
        },
        getImgUrl(i){
            return this.showImgs[i]
        },
        async handlePreview(file) {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            this.previewImage = file.url || file.preview;
            this.previewVisible = true;
        },
        imgHandleChange({ fileList }) {
            this.imgList = fileList;
        },
        beforeUpload(file) {
            return false;
        },
        // 上传图片获取图片url
        uploadImg(file,name){
            let _this = this
            return new Promise((resolve,reject) => {
                let formData = new FormData()
                formData.append('brandId',_this.brandId)
                formData.append('urlName',name)
                formData.append('file',file)
                uploadFile(formData)
                .then(res=>{
                    if(res.success){
                        resolve(res.data)
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 判断用户是否有权限
        hasAuth(role){
            // examineAdoptTrustOrderPaymentVoucher
            var roles = this.$store.getters.roles;
            console.log(roles.indexOf(role),'role')
            if(roles.indexOf(role) != -1){
                return true;
            }
            return false
        },
        // 查看项目详情信息
        showItemInfo(item){
            var type = this.itemTypeList.find(itm => itm.id == item.itemType);
            this.$router.push({path: '/travel/detail', query: { 'travelId': item.id, 'travelName': item.title.title, 'itemTypeName': type ? type.name : ''}})
        },
        // 查看项目套餐信息
        showItemPlan(item){
            var type = this.itemTypeList.find(itm => itm.id == item.itemType);
            this.$router.push({path: '/travel/plan', query: { 'travelId': item.id, 'travelName': item.title.title, 'itemTypeName': type ? type.name : ''}})
        },
    }
}

</script>
<style scoped>
.imgUrl{
    width: 180px;
    height: 100px;
}
.ant-carousel >>> .slick-slide img {
    text-align: center;
    height: 300px;
    line-height: 300px;
    background: #364d79;
    overflow: hidden;
    width: 100%;
}
.ant-carousel >>> .slick-thumb {
  bottom: -15px;
}
.ant-carousel >>> .slick-thumb li {
  width: 60px;
  height: 45px;
}
.ant-carousel >>> .slick-thumb li img {
  width: 100%;
  height: 100%;
  filter: grayscale(100%);
}
.ant-carousel >>> .slick-thumb li.slick-active img {
  filter: grayscale(0%);
}
</style>